import requests ,time, json, re
from io import BytesIO

from django.shortcuts import render,redirect,reverse
from django.http import JsonResponse,HttpResponse
from django.views.generic import View
from django.conf import settings
from apps.account.models import UserInfo

from django_redis import get_redis_connection


from utils.wechat_pramas import get_cookies,format_cookies,parse_info,dict_to_cookie
# Create your viwews here.
_ts = time.time()
UNIXS_TS = int(round(_ts * 1000))


class IndexView(View):
    '''首页'''
    def get(self,request):
        return render(request,"web/index.html")


class LoginView(View):
    '''登陆逻辑'''
    def get(self,request,*args,**kwargs):
        return render(request,'web/login.html')

# 生成二维码
class GetImage(View):
    '''生成二维码的'''
    def get(self, request):

        UserAgent = request.META.get("HTTP_USER_AGENT")
        cookies_dict = get_cookies(UserAgent)  # 获取初步cookies
        # print(cookies_dict)
        lists = []
        for k, v in cookies_dict.items():
            temp = str(k) + "=" + str(v) + ";"
            lists.append(temp)
        headers = {
            'authority': "mp.weixin.qq.com",
            'method': "GET",
            'path': "/cgi-bin/scanloginqrcode?action=getqrcode&random=1591605721430",
            'scheme': "https",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
            'cookie': ''.join(lists),
            'referer': "https://mp.weixin.qq.com/",
            'user-agent': UserAgent,
        }
        img_src = "https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=getqrcode&random={}".format(UNIXS_TS)
        response = requests.get(img_src, headers=headers)
        Response = HttpResponse(BytesIO(response.content))
        for k, v in cookies_dict.items():
            Response.set_cookie(k, v,max_age=3)
        return Response


class CheckLogin(View):
    def get(self,request):
        # 避免爬取太快 延时一秒 轮训
        if request.COOKIES is None:
            time.sleep(1)
            return HttpResponse()
        time.sleep(1)  # 暂停一秒
        UserAgent = request.META.get("HTTP_USER_AGENT")
        wexin_url = "https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1"
        cookies = dict_to_cookie(**request.COOKIES)
        print("check_login cookies", cookies, type(cookies))
        headers = {
            'authority': "mp.weixin.qq.com",
            'method': "GET",
            'path': "/cgi-bin/scanloginqrcode?action=getqrcode&random={}".format(UNIXS_TS),
            'scheme': "https",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
            'cookie': cookies,
            'referer': "https://mp.weixin.qq.com/",
            'user-agent': UserAgent,
        }
        response = requests.get(url=wexin_url, headers=headers)
        data = json.loads(response.text)
        print(data)
        Response = JsonResponse(data)
        for k,v in request.COOKIES.items():
            Response.set_cookie(k, v,max_age=60)
        return Response


class GetToken(View):
    def get(self, request, *args, **kwargs):
        cookies = dict_to_cookie(**request.COOKIES)  # 获取请求的cookies
        print("get token cookies", cookies, type(cookies))
        token = None  # 默认没有token的
        if not cookies:
            return JsonResponse({"status": False, "message": {"数据库cookies为空"}, "respData": ""})
        UserAgent = request.META.get("HTTP_USER_AGENT")
        urls = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login"
        formdata = {
            "userlang": "zh_CN",
            "redirect_url": "",
            "login_type": "3",
            "token": "",
            "lang": "zh_CN",
            "f": "json",
            "ajax": "1"
        }
        headers = {
            'Host': "mp.weixin.qq.com",
            'Connection': "keep-alive",
            'Content-Length': "73",
            'Origin': "https://mp.weixin.qq.com",
            'X-Requested-With': "XMLHttpRequest",
            'User-Agent': UserAgent,
            'Content-Type': "application/x-www-form-urlencoded",
            'Accept': "*/*",
            'Referer': "https://mp.weixin.qq.com/",
            'Accept-Encoding': "gzip, deflate, br",
            'Accept-Language': "zh,en;q=0.9,zh-CN;q=0.8",
            'Cookie': cookies,
        }
        response = requests.post(url=urls, headers=headers, data=formdata)
        resp_data = json.loads(response.text)
        print("返回数据", resp_data)
        if not resp_data.get("base_resp", None):
            return JsonResponse({"status": False, "message": "返回数据失败"})
        if resp_data.get("base_resp", None).get("err_msg", None) != "ok":
            return JsonResponse({"status": False, "message": "数据解析失败"})
        else:
            redirect_url = resp_data.get("redirect_url", None)  # token字段就在这个里面
            if redirect_url:
                re_data = re.findall(r"token=(\d+)", redirect_url)
                token = ''.join(re_data)  # 解析出token字段
                print("最后的token",token)
        if not token:
            return JsonResponse({"status": False, "message": "Token解析失败"})
        # 解析cookie字段
        cookie_new = format_cookies(response.headers['Set-Cookie'])
        print("花里花哨",cookie_new)
        cookie_dicts = {}
        for line in cookie_new.split(';'):
            if len(line.split('=')) > 1:
                key, value = line.split('=', 1)
                cookie_dicts[key.strip()] = value.strip()
        finall_cookies = cookies + str(cookie_new)
        # 把数据保存到reids中
        user_dict = parse_info(UserAgent,finall_cookies,token)
        # 把数据保存到数据库中
        try:
            user = UserInfo.objects.get(user_name=user_dict.get("user_name", None))
        except UserInfo.DoesNotExist:
            user = None
        if not user:
            user = UserInfo.objects.create(user_name=user_dict.get("user_name", None),
                                           wechat_code=user_dict.get("wechat_code", None),
                                           introduce=user_dict.get("introduce", None),
                                           token=token,cookies=finall_cookies,
                                           address = user_dict.get("address", None),
                                           authentication_status = 2 if user_dict.get("authentication_status", None) == "未认证" else 1,
                                           profile_url=user_dict.get("logo", None)
                                           )
            user.save()
        else:
            # 更新token和cookies
            user.token = token
            user.cookies = finall_cookies
            user.save()
        print(user_dict)
        Response = JsonResponse({"status": True, 'data': "/index/","UserInfo":user_dict})
        # Response.set_cookie("finally",finall_cookies,max_age=18000)
        for k,v in cookie_dicts.items():
            Response.set_cookie(k, v, max_age=18000)
        return Response
        # 获取用户的用户名 头像等信息


class LogoutView(View):
    def get(self,request):
        print(request.COOKIES)
        Response = redirect(reverse("account:index"))
        for k,v in request.COOKIES.items():
            Response.delete_cookie(k)
        return Response














